package kuzmenkov.applet;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.util.logging.Logger;


public class ImageComp extends Component {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5898021327041803230L;

	private Logger log = Logger.getLogger(this.getClass().getPackage().getName());
	/**
	 * An image that shows on the component
	 */
	private Image image;
	
	public ImageComp(Image image) {
		this();
		setImage(image);
	}

	public ImageComp (){
	}
	
	
	public void setImage(Image image) {
		this.image = image;
	}

	public Image getImage() {
		return image;
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		if (image!=null){
			Graphics2D g2d = (Graphics2D) g;
			g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 
					RenderingHints.VALUE_INTERPOLATION_BICUBIC);

			
			int compWidth = getWidth();
			int compHeight = getHeight();
			int imageWidth = image.getWidth(null);
			int imageHeight = image.getHeight(null);
			float factor = 1f;
			
			log.finer("compWidth="+compWidth+", compHeight="+compHeight+
					", imageWidth="+imageWidth+", imageHeight="+imageHeight);
			
			int width = 0;
			int height = 0;

			if (imageWidth > compWidth && imageHeight < compHeight){
				factor = (float) compWidth/imageWidth;
				width = compWidth;
				height = (int)(imageHeight*factor);
			} else if (imageHeight > compHeight && imageWidth < compWidth) {
				factor = (float)compHeight / imageHeight;
				width = (int)(imageWidth*factor);
				height = compHeight;
			} else if (imageWidth > compWidth && imageHeight > compHeight){
				if ((float)imageWidth/compWidth > (float)imageHeight/compHeight){
					factor = (float)compWidth / imageWidth;
					width = compWidth;
					height = (int)(imageHeight*factor);
				} else {
					factor = (float)compHeight / imageHeight;
					width = (int)(imageWidth*factor);
					height = compHeight;
				}
			} else if (imageWidth < compWidth && imageHeight < compHeight) {
				width = imageWidth;
				height = imageHeight;
			} else 
				assert (false);
						
			int x = (compWidth - width)/2;
			int y = (compHeight - height)/2;
			
			log.finer("width="+width+", height="+height+", x="+x+", y="+y+", factor="+factor);
			g.drawImage(image, x, y, width, height, null);
			
		}
	}
	
}
